package com.maxmlr.music.common.config;

import javax.servlet.http.HttpServletRequest;

import com.maxmlr.music.common.bean.ResultBean;
import com.maxmlr.music.common.enums.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.maxmlr.music.common.util.HttpUtil;

/**
 * 
 * @Package com.maxmlr.music.common.config
 * @ClassName WebLogAspect
 * @Description 日志切面
 * @author max
 * @since 2018年12月15日 下午6:12:49 
 * @version 1.0
 * @Copyright Copyright (c) 2018: www.maxmlr.com.
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

	@Pointcut("execution (* com.maxmlr.music.*.controller..*.* (..))")
	private void anyMethod() {
	} // 声明一个切入点，anyMethod为切入点名称

	
	/**
	 * 
	 * @Title doAround
	 * @Description 环绕通知
	 * @author max
	 * @since 2018年12月15日 下午6:13:09
	 * @param pjp
	 * @return
	 * @throws Throwable
	 */
	@Around("anyMethod()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		HttpServletRequest request = HttpUtil.getHttpServletRequest();
		Class<?> declaringType = pjp.getTarget().getClass();// 类名

		// 记录下请求内容
		log.info("请求<{}> : {} ", request.getMethod(), request.getRequestURL().toString());
		log.info("请求CLASS_METHOD : " + declaringType.getName() + "." + pjp.getSignature().getName());
		try {
			log.info("请求参数ARGS : " + JSON.toJSONString(pjp.getArgs()));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 开始
        Object retVal = null;
		try {
			retVal = pjp.proceed();
		} catch (Exception e) {
			log.error("请求响应发现未知异常:",e);
			retVal= ResultBean.error(ErrorCode.ERROR);
		}
        stopWatch.stop();
        // 结束
		log.info("请求响应耗时: {} ms" , stopWatch.getTotalTimeMillis());
		log.info("请求响应信息RESPONSE : " + JSON.toJSONString(retVal));
        return retVal;
	}
	
}